/**
 * 订单数据安全包装器
 * 处理订单数据中的undefined、null值，提供默认值和格式化功能
 */

class OrderDataSafeWrapper {
  constructor() {
    // 默认值配置
    this.defaults = {
      order: {
        id: '',
        orderNumber: '未知订单号',
        status: 'unknown',
        paymentStatus: 'unknown',
        paymentMethod: 'unknown',
        totalPoints: 0,
        finalPoints: 0,
        discountPoints: 0,
        pointsUsed: 0,
        pointsEarned: 0,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        items: [],
        user: {},
        product: {}
      },
      orderItem: {
        id: '',
        productId: '',
        productName: '未知商品',
        quantity: 0,
        unitPoints: 0,
        totalPoints: 0,
        unitPoints: 0,
        specifications: {}
      },
      user: {
        id: '',
        nickname: '未知用户',
        phone: '未绑定',
        email: '未绑定'
      },
      product: {
        id: '',
        name: '未知商品',
        pointsPrice: 0,
        images: [],
        description: ''
      }
    }

    // 状态文本映射
    this.statusTexts = {
      order: {
        pending: '待处理',
        confirmed: '已确认',
        processing: '处理中',
        printing: '打印中',
        completed: '已完成',
        cancelled: '已取消',
        unknown: '未知状态'
      },
      payment: {
        pending: '待确认',
        confirmed: '已确认',
        completed: '已完成',
        unknown: '未知状态'
      },
      exchangeMethod: {
        points: '积分兑换',
        unknown: '未知方式'
      }
    }
  }

  /**
   * 安全获取订单数据
   * @param {Object} order - 订单对象
   * @param {string} field - 字段路径，支持点号分隔
   * @param {*} defaultValue - 默认值
   * @returns {*} 安全的字段值
   */
  safeGet(order, field, defaultValue = '') {
    if (!order || typeof order !== 'object') {
      return defaultValue
    }

    const fields = field.split('.')
    let value = order

    for (const f of fields) {
      if (value === null || value === undefined || typeof value !== 'object') {
        return defaultValue
      }
      value = value[f]
    }

    return value !== null && value !== undefined ? value : defaultValue
  }

  /**
   * 格式化订单数据用于显示
   * @param {Object} order - 原始订单数据
   * @returns {Object} 格式化后的订单数据
   */
  formatOrderForDisplay(order) {
    if (!order) {
      return { ...this.defaults.order }
    }

    const formatted = {
      // 基本信息
      id: this.safeGet(order, 'id', this.defaults.order.id),
      orderNumber: this.safeGet(order, 'orderNumber') || 
                   this.safeGet(order, 'order_number') || 
                   this.safeGet(order, 'order_no', this.defaults.order.orderNumber),
      
      // 状态信息
      status: this.safeGet(order, 'status', this.defaults.order.status),
      statusText: this.getStatusText('order', this.safeGet(order, 'status')),
      exchangeStatus: this.safeGet(order, 'exchangeStatus') || 
                     this.safeGet(order, 'exchange_status', this.defaults.order.paymentStatus),
      exchangeStatusText: this.getStatusText('payment', 
        this.safeGet(order, 'exchangeStatus') || this.safeGet(order, 'exchange_status')),
      exchangeMethod: this.safeGet(order, 'exchangeMethod') || 
                     this.safeGet(order, 'exchange_method', 'points'),
      exchangeMethodText: this.getStatusText('exchangeMethod', 
        this.safeGet(order, 'exchangeMethod') || this.safeGet(order, 'exchange_method')),

      // 积分信息
      totalPoints: this.safeGetNumber(order, 'totalPoints') || 
                   this.safeGetNumber(order, 'total_points', this.defaults.order.totalPoints),
      finalPoints: this.safeGetNumber(order, 'finalPoints') || 
                   this.safeGetNumber(order, 'final_points', this.defaults.order.finalPoints),
      discountPoints: this.safeGetNumber(order, 'discountPoints') || 
                      this.safeGetNumber(order, 'discount_points', this.defaults.order.discountPoints),

      // 积分信息
      pointsUsed: this.safeGetNumber(order, 'pointsUsed') || 
                  this.safeGetNumber(order, 'points_used', this.defaults.order.pointsUsed),
      pointsEarned: this.safeGetNumber(order, 'pointsEarned') || 
                    this.safeGetNumber(order, 'points_earned', this.defaults.order.pointsEarned),
      totalPoints: this.safeGetNumber(order, 'totalPoints') || 
                   this.safeGetNumber(order, 'total_points', 0),

      // 数量信息
      totalQuantity: this.safeGetNumber(order, 'totalQuantity') || 
                     this.safeGetNumber(order, 'total_quantity', 0),

      // 时间信息
      createdAt: this.safeGet(order, 'createdAt') || 
                 this.safeGet(order, 'created_at', this.defaults.order.createdAt),
      updatedAt: this.safeGet(order, 'updatedAt') || 
                 this.safeGet(order, 'updated_at', this.defaults.order.updatedAt),

      // 预约码
      reservationCode: this.safeGet(order, 'reservationCode') || 
                       this.safeGet(order, 'reservation_code', ''),

      // 订单类型
      type: this.safeGet(order, 'type', 'offline'),
      typeText: this.getOrderTypeText(this.safeGet(order, 'type', 'offline')),

      // 商品列表
      items: this.formatOrderItems(this.safeGet(order, 'items', [])),

      // 用户信息
      user: this.formatUserInfo(this.safeGet(order, 'user') || this.safeGet(order, 'userId')),

      // 备注信息
      notes: this.safeGet(order, 'notes', ''),
      adminNotes: this.safeGet(order, 'adminNotes') || this.safeGet(order, 'admin_notes', ''),

      // 配送信息
      deliveryInfo: this.formatDeliveryInfo(this.safeGet(order, 'deliveryInfo') || this.safeGet(order, 'delivery_info'))
    }

    // 计算总数量（如果没有提供）
    if (!formatted.totalQuantity && formatted.items.length > 0) {
      formatted.totalQuantity = formatted.items.reduce((sum, item) => sum + item.quantity, 0)
    }

    return formatted
  }

  /**
   * 格式化订单商品列表
   * @param {Array} items - 商品列表
   * @returns {Array} 格式化后的商品列表
   */
  formatOrderItems(items) {
    if (!Array.isArray(items)) {
      return []
    }

    return items.map(item => this.formatOrderItem(item))
  }

  /**
   * 格式化单个订单商品
   * @param {Object} item - 商品项
   * @returns {Object} 格式化后的商品项
   */
  formatOrderItem(item) {
    if (!item) {
      return { ...this.defaults.orderItem }
    }

    const formatted = {
      id: this.safeGet(item, 'id') || this.safeGet(item, '_id', this.defaults.orderItem.id),
      productId: this.safeGet(item, 'productId') || 
                 this.safeGet(item, 'product_id', this.defaults.orderItem.productId),
      productName: this.safeGet(item, 'productName') || 
                   this.safeGet(item, 'product_name') ||
                   this.safeGet(item, 'name', this.defaults.orderItem.productName),
      quantity: this.safeGetNumber(item, 'quantity', this.defaults.orderItem.quantity),
      unitPoints: this.safeGetNumber(item, 'unitPoints') || 
                  this.safeGetNumber(item, 'unit_points', this.defaults.orderItem.unitPoints),
      totalPoints: this.safeGetNumber(item, 'totalPoints') || 
                   this.safeGetNumber(item, 'total_points', this.defaults.orderItem.totalPoints),
      specifications: this.safeGet(item, 'specifications', this.defaults.orderItem.specifications),

      // 商品详情（如果有关联）
      product: this.formatProductInfo(this.safeGet(item, 'product') || this.safeGet(item, 'productId'))
    }

    // 计算总积分（如果没有提供）
    if (!formatted.totalPoints && formatted.unitPoints && formatted.quantity) {
      formatted.totalPoints = formatted.unitPoints * formatted.quantity
    }

    return formatted
  }

  /**
   * 格式化用户信息
   * @param {Object} user - 用户对象
   * @returns {Object} 格式化后的用户信息
   */
  formatUserInfo(user) {
    if (!user || typeof user !== 'object') {
      return { ...this.defaults.user }
    }

    return {
      id: this.safeGet(user, 'id') || this.safeGet(user, '_id', this.defaults.user.id),
      nickname: this.safeGet(user, 'nickname') || 
                this.safeGet(user, 'username', this.defaults.user.nickname),
      phone: this.safeGet(user, 'phone', this.defaults.user.phone),
      email: this.safeGet(user, 'email', this.defaults.user.email)
    }
  }

  /**
   * 格式化商品信息
   * @param {Object} product - 商品对象
   * @returns {Object} 格式化后的商品信息
   */
  formatProductInfo(product) {
    if (!product || typeof product !== 'object') {
      return { ...this.defaults.product }
    }

    return {
      id: this.safeGet(product, 'id') || this.safeGet(product, '_id', this.defaults.product.id),
      name: this.safeGet(product, 'name', this.defaults.product.name),
      pointsPrice: this.safeGetNumber(product, 'pointsPrice') || 
                   this.safeGetNumber(product, 'points_price', this.defaults.product.pointsPrice),
      images: this.safeGetArray(product, 'images', this.defaults.product.images),
      imageUrl: this.safeGet(product, 'imageUrl') || 
                this.safeGet(product, 'image_url') ||
                (this.safeGetArray(product, 'images', [])[0] || ''),
      description: this.safeGet(product, 'description', this.defaults.product.description)
    }
  }

  /**
   * 格式化配送信息
   * @param {Object} deliveryInfo - 配送信息
   * @returns {Object} 格式化后的配送信息
   */
  formatDeliveryInfo(deliveryInfo) {
    if (!deliveryInfo || typeof deliveryInfo !== 'object') {
      return null
    }

    return {
      deliveryMethod: this.safeGet(deliveryInfo, 'deliveryMethod') || 
                      this.safeGet(deliveryInfo, 'delivery_method', 'pickup'),
      deliveryMethodText: this.getDeliveryMethodText(
        this.safeGet(deliveryInfo, 'deliveryMethod') || 
        this.safeGet(deliveryInfo, 'delivery_method', 'pickup')
      ),
      recipientName: this.safeGet(deliveryInfo, 'recipientName') || 
                     this.safeGet(deliveryInfo, 'recipient_name', ''),
      phone: this.safeGet(deliveryInfo, 'phone', ''),
      address: this.safeGet(deliveryInfo, 'address', ''),
      deliveryPoints: this.safeGetNumber(deliveryInfo, 'deliveryPoints') || 
                      this.safeGetNumber(deliveryInfo, 'delivery_points', 0)
    }
  }

  /**
   * 安全获取数字类型值
   * @param {Object} obj - 对象
   * @param {string} field - 字段名
   * @param {number} defaultValue - 默认值
   * @returns {number} 数字值
   */
  safeGetNumber(obj, field, defaultValue = 0) {
    const value = this.safeGet(obj, field, defaultValue)
    const num = parseFloat(value)
    return isNaN(num) ? defaultValue : num
  }

  /**
   * 安全获取数组类型值
   * @param {Object} obj - 对象
   * @param {string} field - 字段名
   * @param {Array} defaultValue - 默认值
   * @returns {Array} 数组值
   */
  safeGetArray(obj, field, defaultValue = []) {
    const value = this.safeGet(obj, field, defaultValue)
    return Array.isArray(value) ? value : defaultValue
  }

  /**
   * 获取状态文本
   * @param {string} type - 状态类型
   * @param {string} status - 状态值
   * @returns {string} 状态文本
   */
  getStatusText(type, status) {
    if (!status || !this.statusTexts[type]) {
      return this.statusTexts[type]?.unknown || '未知状态'
    }
    return this.statusTexts[type][status] || status
  }

  /**
   * 获取订单类型文本
   * @param {string} type - 订单类型
   * @returns {string} 类型文本
   */
  getOrderTypeText(type) {
    const typeMap = {
      offline: '到店兑换',
      online: '在线处理',
      delivery: '配送上门'
    }
    return typeMap[type] || type
  }

  /**
   * 获取配送方式文本
   * @param {string} method - 配送方式
   * @returns {string} 配送方式文本
   */
  getDeliveryMethodText(method) {
    const methodMap = {
      pickup: '到店自取',
      delivery: '配送上门',
      express: '快递配送'
    }
    return methodMap[method] || method
  }

  /**
   * 验证订单数据完整性
   * @param {Object} order - 订单数据
   * @returns {Object} 验证结果
   */
  validateOrderData(order) {
    const errors = []
    const warnings = []

    if (!order) {
      errors.push('订单数据为空')
      return { isValid: false, errors, warnings }
    }

    // 必需字段检查
    const requiredFields = ['id', 'orderNumber', 'status']
    for (const field of requiredFields) {
      if (!this.safeGet(order, field)) {
        errors.push(`缺少必需字段: ${field}`)
      }
    }

    // 数据类型检查
    const numberFields = ['totalPoints', 'finalPoints']
    for (const field of numberFields) {
      const value = this.safeGet(order, field)
      if (value !== '' && isNaN(parseFloat(value))) {
        warnings.push(`字段 ${field} 不是有效数字: ${value}`)
      }
    }

    // 商品列表检查
    const items = this.safeGet(order, 'items', [])
    if (!Array.isArray(items)) {
      errors.push('商品列表格式错误')
    } else if (items.length === 0) {
      warnings.push('订单没有商品')
    }

    return {
      isValid: errors.length === 0,
      errors,
      warnings
    }
  }

  /**
   * 格式化时间显示
   * @param {string|Date} time - 时间
   * @param {string} format - 格式类型
   * @returns {string} 格式化后的时间
   */
  formatTime(time, format = 'datetime') {
    if (!time) return ''

    try {
      const date = new Date(time)
      if (isNaN(date.getTime())) return ''

      const now = new Date()
      const diff = now - date

      if (format === 'relative') {
        if (diff < 60000) { // 1分钟内
          return '刚刚'
        } else if (diff < 3600000) { // 1小时内
          return Math.floor(diff / 60000) + '分钟前'
        } else if (diff < 86400000) { // 1天内
          return Math.floor(diff / 3600000) + '小时前'
        } else {
          return Math.floor(diff / 86400000) + '天前'
        }
      }

      // 默认格式
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')

      if (format === 'date') {
        return `${year}-${month}-${day}`
      } else if (format === 'time') {
        return `${hours}:${minutes}`
      } else {
        return `${year}-${month}-${day} ${hours}:${minutes}`
      }
    } catch (error) {
      console.error('时间格式化失败:', error)
      return ''
    }
  }

  /**
   * 格式化积分显示
   * @param {number} points - 积分
   * @returns {string} 格式化后的积分
   */
  formatPointsAmount(points) {
    const num = this.safeGetNumber({ points }, 'points', 0)
    return `${num}积分`
  }

  /**
   * 格式化积分显示
   * @param {number} points - 积分
   * @returns {string} 格式化后的积分
   */
  formatPoints(points) {
    const num = this.safeGetNumber({ points }, 'points', 0)
    return `${num}积分`
  }

  /**
   * 获取订单状态样式类
   * @param {string} status - 订单状态
   * @returns {string} CSS类名
   */
  getStatusClass(status) {
    const classMap = {
      pending: 'status-pending',
      confirmed: 'status-confirmed',
      processing: 'status-processing',
      printing: 'status-printing',
      completed: 'status-completed',
      cancelled: 'status-cancelled'
    }
    return classMap[status] || 'status-unknown'
  }

  /**
   * 获取支付状态样式类
   * @param {string} status - 支付状态
   * @returns {string} CSS类名
   */
  getPaymentStatusClass(status) {
    const classMap = {
      unpaid: 'payment-unpaid',
      paid: 'payment-paid',
      refunded: 'payment-refunded'
    }
    return classMap[status] || 'payment-unknown'
  }
}

// 创建全局实例
const orderDataSafe = new OrderDataSafeWrapper()

// 导出便捷方法
export const safeGetOrderData = (order, field, defaultValue) => {
  return orderDataSafe.safeGet(order, field, defaultValue)
}

export const formatOrderForDisplay = (order) => {
  return orderDataSafe.formatOrderForDisplay(order)
}

export const validateOrderData = (order) => {
  return orderDataSafe.validateOrderData(order)
}

export const formatOrderTime = (time, format) => {
  return orderDataSafe.formatTime(time, format)
}

export const formatOrderPoints = (points) => {
  return orderDataSafe.formatPointsAmount(points)
}

export const getOrderStatusText = (status) => {
  return orderDataSafe.getStatusText('order', status)
}

export const getPaymentStatusText = (status) => {
  return orderDataSafe.getStatusText('payment', status)
}

export const getOrderStatusClass = (status) => {
  return orderDataSafe.getStatusClass(status)
}

export const getPaymentStatusClass = (status) => {
  return orderDataSafe.getPaymentStatusClass(status)
}

export default orderDataSafe